<template>
  <div class="classroom-simple-apply">
    <!-- 申请表单区域 -->
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="apply-form">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="申请人" prop="userName">
            <el-input v-model="form.userName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计人数" prop="expectedPeople">
            <el-input v-model.number="form.expectedPeople" placeholder="请输入预计人数" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="申请类型" prop="applicationType">
            <el-select v-model="form.applicationType" placeholder="请选择申请类型">
              <el-option 
                v-for="(label, value) in applicationTypeLabelMap" 
                :key="value" 
                :label="label" 
                :value="value" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="教室类型" prop="classroomType">
            <el-select v-model="form.classroomType" placeholder="请选择教室类型">
              <el-option 
                v-for="(label, value) in classroomTypeLabelMap" 
                :key="value" 
                :label="label" 
                :value="value" 
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="申请日期" prop="applyDate">
            <el-date-picker v-model="form.applyDate" type="date" placeholder="选择日期" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开始时间" prop="startTime">
            <el-time-picker v-model="form.startTime" placeholder="开始时间" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结束时间" prop="endTime">
            <el-time-picker v-model="form.endTime" placeholder="结束时间" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="设备需求" prop="equipmentNeeds">
            <el-checkbox-group v-model="form.equipmentNeedsList">
              <el-checkbox label="投影仪" />
              <el-checkbox label="电脑" />
              <el-checkbox label="音响" />
              <el-checkbox label="白板" />
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="用途" prop="purpose">
            <el-select
              v-model="form.purpose"
              placeholder="请选择用途"
              filterable
              allow-create
              default-first-option
              style="width: 100%"
            >
              <el-option
                v-for="item in purposeOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 可用教室列表区域 -->
    <div class="classroom-list-section">
      <div class="section-title">可用教室列表</div>
      <el-row :gutter="16">
        <el-col v-for="room in classroomList" :key="room.classroomId" :span="8" style="margin-bottom: 16px;">
          <el-card class="classroom-card" :class="{ 'selected-card': form.classroomIds.includes(room.classroomId) }" @click="toggleClassroom(room.classroomId)">
            <div class="card-header">
              <span class="room-code">{{ room.classroomCode || '-' }}</span>
              <el-tag v-if="room.status === 'AVAILABLE'" type="success" size="small">可用</el-tag>
              <el-tag v-else-if="room.status === 'MAINTENANCE'" type="warning" size="small">维护中</el-tag>
              <el-tag v-else-if="room.status === 'DISABLED'" type="info" size="small">停用</el-tag>
              <el-tag v-else type="info" size="small">{{ room.status }}</el-tag>
            </div>
            <div class="card-body">
              <div><b>教室编号：</b>{{ room.classroomCode || '-' }}</div>
              <div><b>教室ID：</b>{{ room.classroomId || '-' }}</div>
              <div><b>校区：</b>{{ room.campus || '-' }}</div>
              <div><b>楼宇：</b>{{ room.building || '-' }}</div>
              <div><b>楼层：</b>{{ room.floor ? room.floor + '层' : '-' }}</div>
              <div><b>容量：</b>{{ room.capacity ? room.capacity + '人' : '-' }}</div>
              <div><b>教室类型：</b>{{ room.classroomType || '-' }}</div>
              <div><b>设备：</b>{{ (room.equipmentList || []).join('、') || '-' }}</div>
              <div><b>状态：</b>{{ room.status || '-' }}</div>
              <div><b>创建时间：</b>{{ room.createTime || '-' }}</div>
              <div><b>更新时间：</b>{{ room.updateTime || '-' }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div class="selected-info">已选择 {{ form.classroomIds.length }} 间教室</div>
    </div>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="resetForm">重置</el-button>
      <el-button type="primary" @click="submitForm">提交申请</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { submitClassroomApplication, getAvailableClassrooms, getClassroomList } from '@/api/classroom'
import { applicationTypeLabelMap, classroomTypeLabelMap } from '@/utils/statusMap'
import dayjs from 'dayjs'

// 表单数据结构
const form = reactive({
  userName: '张三（教师）', // 实际应从登录信息获取
  userId: 1, // 实际应从登录信息获取
  applicationType: '',
  classroomType: '',
  applyDate: '',
  startTime: '',
  endTime: '',
  expectedPeople: undefined,
  equipmentNeedsList: [], // 多选
  purpose: '',
  classroomIds: [] as number[],
})

// 校验规则
const rules = {
  applicationType: [{ required: true, message: '请选择申请类型', trigger: 'change' }],
  classroomType: [{ required: true, message: '请选择教室类型', trigger: 'change' }],
  applyDate: [{ required: true, message: '请选择日期', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  expectedPeople: [{ required: true, message: '请输入预计人数', trigger: 'blur' }],
  purpose: [{ required: true, message: '请输入用途', trigger: 'blur' }],
}

interface ClassroomItem {
  classroomId: number
  classroomCode: string
  campus: string
  building: string
  floor: number
  capacity: number
  classroomType: string
  equipmentList: string[]
  status: string
  createTime?: string
  updateTime?: string
}

const classroomList = ref<ClassroomItem[]>([])

// 常用用途选项
const purposeOptions = [
  '上课',
  '考试',
  '会议',
  '实验',
  '讲座',
  '培训'
]

async function fetchAvailableClassrooms() {
  try {
    const params = {
      date: form.applyDate ? dayjs(form.applyDate).format('YYYY-MM-DD') : '',
      startTime: form.startTime ? dayjs(form.startTime).format('HH:mm') : '',
      endTime: form.endTime ? dayjs(form.endTime).format('HH:mm') : '',
      classroomType: form.classroomType,
      capacity: form.expectedPeople
    }
    // 增加日志，便于调试
    console.log('请求可用教室参数:', params)
    const res = await getAvailableClassrooms(params)
    console.log('可用教室接口返回:', res)
    classroomList.value = Array.isArray(res.data) ? res.data : []
  } catch (e) {
    classroomList.value = []
    console.error('获取可用教室失败', e)
  }
}

// 监听表单关键字段变化，自动请求可用教室
watch(
  () => [form.applyDate, form.startTime, form.endTime, form.classroomType, form.expectedPeople],
  ([applyDate, startTime, endTime, classroomType, expectedPeople]) => {
    // 只有所有筛选条件都填写后才请求
    if (applyDate && startTime && endTime && classroomType && expectedPeople) {
      fetchAvailableClassrooms()
    } else {
      classroomList.value = []
    }
  }
)

onMounted(() => {
  fetchAvailableClassrooms()
  
})

// 选择/取消选择教室
function toggleClassroom(id: number) {
  const idx = form.classroomIds.indexOf(id)
  if (idx === -1) {
    form.classroomIds.push(id)
  } else {
    form.classroomIds.splice(idx, 1)
  }
}

// 重置表单
function resetForm() {
  form.applicationType = ''
  form.classroomType = ''
  form.applyDate = ''
  form.startTime = ''
  form.endTime = ''
  form.expectedPeople = undefined
  form.equipmentNeedsList = []
  form.purpose = ''
  form.classroomIds = []
}

// 提交表单
async function submitForm() {
  const equipmentNeeds = form.equipmentNeedsList.join(',')
  const submitData = {
    applicationType: form.applicationType,
    classroomType: form.classroomType,
    userId: form.userId,
    applyDate: form.applyDate ? dayjs(form.applyDate).format('YYYY-MM-DD') : '',
    startTime: form.startTime ? dayjs(form.startTime).format('HH:mm') : '',
    endTime: form.endTime ? dayjs(form.endTime).format('HH:mm') : '',
    purpose: form.purpose,
    expectedPeople: form.expectedPeople || 0,
    equipmentNeeds,
    classroomIds: form.classroomIds
  }
  console.log(submitData)
  try {
    const res = await submitClassroomApplication(submitData)
    console.log('后端返回：', res)
    ElMessage.success('申请提交成功！')
    resetForm()
  } catch (e) {
    ElMessage.error('申请提交失败！')
  }
}
</script>

<style scoped>
.classroom-simple-apply {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
}
.apply-form {
  margin-bottom: 32px;
}
.classroom-list-section {
  margin-bottom: 24px;
}
.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
}
.classroom-card {
  min-height: 210px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}
.card-body > div {
  margin-bottom: 4px;
  font-size: 15px;
}
.room-code {
  font-weight: bold;
  font-size: 16px;
}
.selected-info {
  margin-top: 12px;
  color: #409eff;
}
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
}
.selected-card {
  border: 2px solid #409eff !important;
  box-shadow: 0 0 8px #409eff33;
  background: #f0f8ff;
}
</style> 